package com.atguigu.gmall.pms.service.impl;

import com.atguigu.gmall.pms.entity.*;
import com.atguigu.gmall.pms.feign.GmallSmsClient;
import com.atguigu.gmall.pms.mapper.SkuMapper;
import com.atguigu.gmall.pms.mapper.SpuDescMapper;
import com.atguigu.gmall.pms.service.SkuAttrValueService;
import com.atguigu.gmall.pms.service.SkuImagesService;
import com.atguigu.gmall.pms.service.SpuDescService;
import com.atguigu.gmall.pms.vo.SpuAttrValueVo;
import com.atguigu.gmall.pms.vo.SkuVO;
import com.atguigu.gmall.pms.vo.SpuVO;
import com.atguigu.gmall.sms.vo.SalesVO;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.common.bean.PageResultVo;
import com.atguigu.gmall.common.bean.PageParamVo;

import com.atguigu.gmall.pms.mapper.SpuMapper;
import com.atguigu.gmall.pms.service.SpuService;


@Service("spuService")
public class SpuServiceImpl extends ServiceImpl<SpuMapper, SpuEntity> implements SpuService {

    @Autowired
    private SpuDescMapper spuDescMapper;

    @Autowired
    private SpuAttrValueServiceImpl spuAttrValueService;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuAttrValueService skuAttrValueService;

    @Autowired
    private GmallSmsClient smsClient;

    @Autowired
    private SpuDescService descService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public PageResultVo queryPage(PageParamVo paramVo) {
        IPage<SpuEntity> page = this.page(
                paramVo.getPage(),
                new QueryWrapper<SpuEntity>()
        );

        return new PageResultVo(page);
    }

    @Override
    public PageResultVo querySpuByCid(Long categoryId, PageParamVo pageParamVo) {
        //组装查询条件
        QueryWrapper<SpuEntity> wrapper = new QueryWrapper<>();
        if (categoryId!=0){
            wrapper.eq("category_id",categoryId);
        }

        //获取检索条件
        String key = pageParamVo.getKey();
        if (StringUtils.isNotBlank(key)){
            wrapper.and(t->t.eq("id",key).or().like("name",key));
        }

        //组装分页条件
        IPage<SpuEntity> page = this.page(
                pageParamVo.getPage(),
                wrapper
        );

        return new PageResultVo(page);
    }

    @Override
    @GlobalTransactional
    public void saveDetail(SpuVO spu) {
        //保存商品信息
        //1.1 保存表 pms_spu
        saveSpuInfo(spu);
        Long spuId = spu.getId();

        //1.2 保存表 pms_spu_desc
        descService.saveSpuDesc(spu, spuId);

        //int a = 1/0;
        //1.3 保存表 pms_spu_attr_value
        saveBaseAttr(spu, spuId);
        //2.1 保存表 pms_sku
        saveSkuInfo(spu, spuId);
    }

    private void saveSkuInfo(SpuVO spu, Long spuId) {
        List<SkuVO> skuVOS = spu.getSkus();
        if (!CollectionUtils.isEmpty(skuVOS)){
            skuVOS.forEach(skuVO -> {
                SkuEntity skuEntity = new SkuEntity();
                BeanUtils.copyProperties(skuVO,skuEntity);
                //设置品牌和分类信息
                skuEntity.setBrandId(spu.getBrandId());
                skuEntity.setCategoryId(spu.getCategoryId());
                //设置默认图片信息
                List<String> images = skuVO.getImages();
                if (!CollectionUtils.isEmpty(images)){
                    skuEntity.setDefaultImage(skuEntity.getDefaultImage()==null? images.get(0):skuEntity.getDefaultImage());
                }
                skuEntity.setSpuId(spuId);
                skuMapper.insert(skuEntity);

                //获取skuId
                Long skuId = skuEntity.getId();

                //2.2 保存表 pms_sku_images
                if (!CollectionUtils.isEmpty(images)){
                    List<SkuImagesEntity> skuImagesEntitys = images.stream().map(image -> {
                        SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                        skuImagesEntity.setSkuId(skuId);
                        skuImagesEntity.setDefaultStatus(StringUtils.equals(skuEntity.getDefaultImage(), image) ? 1 : 0);
                        skuImagesEntity.setUrl(image);
                        return skuImagesEntity;
                    }).collect(Collectors.toList());
                    skuImagesService.saveBatch(skuImagesEntitys);
                }
                //2.3 保存表 pms_sku_attr_value
                List<SkuAttrValueEntity> saleAttrs = skuVO.getSaleAttrs();
                saleAttrs.forEach(saleAttr->{
                    saleAttr.setSkuId(skuId);
                });
                skuAttrValueService.saveBatch(saleAttrs);

                //3保存营销信息 需要远程调用
                SalesVO salesVO = new SalesVO();
                //拷贝属性，设置skuId
                BeanUtils.copyProperties(skuVO,salesVO);
                salesVO.setSkuId(skuId);
                smsClient.saveSales(salesVO);
            });
        }
        //发送消息到mq spuId
        rabbitTemplate.convertAndSend("PMS.INSERT.EXCHANGE","item.insert",spuId);
    }

    private void saveBaseAttr(SpuVO spu, Long spuId) {
        List<SpuAttrValueVo> baseAttrs = spu.getBaseAttrs();
        if (!CollectionUtils.isEmpty(baseAttrs)){
            List<SpuAttrValueEntity> spuAttrValueEntitys = baseAttrs.stream().map(baseAttr -> {
                SpuAttrValueEntity spuAttrValueEntity = new SpuAttrValueEntity();
                spuAttrValueEntity.setSpuId(spuId);
                spuAttrValueEntity.setAttrId(baseAttr.getAttrId());
                spuAttrValueEntity.setAttrValue(baseAttr.getAttrValue());
                spuAttrValueEntity.setAttrName(baseAttr.getAttrName());
                return spuAttrValueEntity;
            }).collect(Collectors.toList());
            spuAttrValueService.saveBatch(spuAttrValueEntitys);

        }
    }

    private void saveSpuInfo(SpuVO spu) {
        spu.setCreateTime(new Date());
        spu.setUpdateTime(spu.getCreateTime());
        spu.setPublishStatus(1);
        this.save(spu);
    }


}